﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class ModuleSolarPanelFix : PartModule {
	Dictionary<ModuleDeployableSolarPanel, float> originalChargeRates;

	static float POWERCURVE_ONE = 13599840256f;

	public override void OnSave(ConfigNode node) {
		originalChargeRates = new Dictionary<ModuleDeployableSolarPanel, float>();
	}

	public override void OnLoad(ConfigNode node) {
		originalChargeRates = new Dictionary<ModuleDeployableSolarPanel, float>();
	}

	public void FixedUpdate() {
		if (vessel == null || part == null) { return; }

		if (originalChargeRates.Count <= 0) {
			foreach (ModuleDeployableSolarPanel p in part.Modules.OfType<ModuleDeployableSolarPanel>()) {
				originalChargeRates[p] = p.chargeRate;
			}
		}

		float distance = GetSunDistance(part);
		foreach (ModuleDeployableSolarPanel p in part.Modules.OfType<ModuleDeployableSolarPanel>()) {
			FixRate(p, distance, distance / POWERCURVE_ONE);
		}
	}

	private void FixRate(ModuleDeployableSolarPanel p, float distance, float reldistance) {
		p.chargeRate = (originalChargeRates[p] / p.powerCurve.Evaluate(distance)) / (reldistance * reldistance);
	}

	private float GetSunDistance(Part p) {
		return Mathf.Max(1, (p.transform.position - Planetarium.fetch.Sun.transform.position).magnitude);
	}
}
